import React, { useState } from 'react';
import {
  Dialog,
  DialogTitle,
  DialogContent,
  DialogActions,
  Button,
  TextField,
  Box,
  ImageList,
  ImageListItem,
  IconButton,
  CircularProgress,
  Typography
} from '@mui/material';
import { AddPhotoAlternate as AddPhotoIcon, Delete as DeleteIcon } from '@mui/icons-material';

export default function CheckinDialog({ open, activity, onClose, onSubmit }) {
  const [note, setNote] = useState('');
  const [images, setImages] = useState([]);
  const [loading, setLoading] = useState(false);
  const [error, setError] = useState('');

  const handleImageUpload = (event) => {
    const files = Array.from(event.target.files);
    const readers = files.map(file => {
      return new Promise((resolve) => {
        const reader = new FileReader();
        reader.onloadend = () => resolve(reader.result);
        reader.readAsDataURL(file);
      });
    });

    Promise.all(readers).then(results => {
      setImages(prev => [...prev, ...results]);
    });
  };

  const handleDeleteImage = (index) => {
    setImages(prev => prev.filter((_, i) => i !== index));
  };

  const handleSubmit = async () => {
    if (!note && images.length === 0) {
      setError('请添加打卡内容或图片');
      return;
    }

    setLoading(true);
    try {
      await onSubmit(activity._id, { note, images });
      setNote('');
      setImages([]);
      onClose();
    } catch (error) {
      setError(error.message || '打卡失败');
    } finally {
      setLoading(false);
    }
  };

  return (
    <Dialog open={open} onClose={onClose} maxWidth="sm" fullWidth>
      <DialogTitle>
        活动打卡 - {activity?.title}
      </DialogTitle>
      <DialogContent dividers>
        <Box sx={{ display: 'flex', flexDirection: 'column', gap: 2 }}>
          <TextField
            label="打卡记录"
            multiline
            rows={4}
            value={note}
            onChange={(e) => setNote(e.target.value)}
            placeholder="记录一下今天的环保行动..."
          />

          <Box>
            <input
              accept="image/*"
              type="file"
              multiple
              id="image-upload"
              style={{ display: 'none' }}
              onChange={handleImageUpload}
            />
            <label htmlFor="image-upload">
              <Button
                variant="outlined"
                component="span"
                startIcon={<AddPhotoIcon />}
              >
                添加图片
              </Button>
            </label>
          </Box>

          {images.length > 0 && (
            <ImageList sx={{ width: '100%', height: 200 }} cols={3} rowHeight={100}>
              {images.map((image, index) => (
                <ImageListItem key={index} sx={{ position: 'relative' }}>
                  <img
                    src={image}
                    alt={`打卡图片 ${index + 1}`}
                    loading="lazy"
                  />
                  <IconButton
                    onClick={() => handleDeleteImage(index)}
                    sx={{
                      position: 'absolute',
                      right: 5,
                      top: 5,
                      bgcolor: 'rgba(0, 0, 0, 0.5)'
                    }}
                  >
                    <DeleteIcon sx={{ color: 'white' }} />
                  </IconButton>
                </ImageListItem>
              ))}
            </ImageList>
          )}

          {error && (
            <Typography color="error" variant="body2">
              {error}
            </Typography>
          )}
        </Box>
      </DialogContent>
      <DialogActions>
        <Button onClick={onClose}>
          取消
        </Button>
        <Button
          variant="contained"
          onClick={handleSubmit}
          disabled={loading || (!note && images.length === 0)}
        >
          {loading ? <CircularProgress size={24} /> : '提交打卡'}
        </Button>
      </DialogActions>
    </Dialog>
  );
} 